<?php
App::uses('phMagick', 'Lib/Filters');
App::uses('Filters', 'Lib/Filters');

class FiltersController extends AppController {
	
	public function image() {
		
	}
	
	public function image_upload() {
		$this->autoRender = false;
		if (!empty($_FILES)) {
			$tmp = WWW_ROOT . str_replace('/', DS, IMG_TEMP_DIR) . session_id() . '.jpg';
			copy($_FILES['image']['tmp_name'], $tmp);
		}
		echo session_id() . '.jpg';
	}
	
	public function upload() {
		
	}
	
	public function index() {
// 		$Filters = new Filters();
// 		$Filters->thumbnail('input.jpg');
// 		$test = WWW_ROOT . str_replace('/', DS, MASKS_DIR) . 'griseuos_multiply_0.3.jpg';
// 		$Filters = new Filters();
// 		$result = $Filters->alpha($test, 60);
// 		debug($result);
// 		$input = WWW_ROOT . str_replace('/', DS, FILTERS_DIR) . 'beauty.jpg';
// 		$output = WWW_ROOT . str_replace('/', DS, FILTERS_DIR) . 'output.jpg';
// 		$phMagick = new phMagick($input, $output);
// 		$phMagick->beauty();
// 		debug($phMagick->getLog());
	}
	
	public function filter() {
		$this->autoRender = false;
		Configure::write('debug', 0);
		
		if (!isset($this->request->query['filter'])) {
			echo '';
			return;
		}
		
		$filter = $this->request->query['filter'];
		
		$Filters = new Filters();
		$result = $Filters->{$filter}('input.jpg');
		
		if ($result) {
			echo $filter . '.jpg';
		}
	}
	
	public function extract() {
		$this->autoRender = false;
		Configure::write('debug', 0);
// 		debug($this->request->query);
//		$upload = WWW_ROOT . str_replace('/', DS, FILTERS_DIR) . 'upload.jpg';
		$upload = WWW_ROOT . str_replace('/', DS, IMG_TEMP_DIR) . session_id() . '.jpg';
		$output = WWW_ROOT . str_replace('/', DS, FILTERS_DIR) . 'extract.jpg';
		$size = getimagesize($upload);
		$scale = 250 / $size[0];
		$x = round(intval($this->request->query['x']) / $scale);
		$y = round(intval($this->request->query['y']) / $scale);
		$size = round(intval($this->request->query['size']) / $scale);
		$Filters = new Filters();
		$Filters->extract($upload, $output, $x, $y , $size);
	}
}